const $iconUrl = '';
const $closeUrl = '';
const $gotoUrl = '';
const $mainColor = '#2e5cf6';
let isPregressing = true;
let progressNum = 0;
let popupViewWidth = 0;
let callbackFun = () => {};
// 弹窗容器的Padding
let viewContentPadding = 20;
// 弹窗容器的宽度
let viewContentWidth = 0;
// 弹窗容器高度
let popupViewHeight = viewContentPadding * 3 + 60;
// 文字换行
function drawtext(text, maxWidth) {
  let textArr = text.split('');
  let len = textArr.length;
  // 上个节点
  let previousNode = 0;
  // 记录节点宽度
  let nodeWidth = 0;
  // 文本换行数组
  let rowText = [];
  // 如果是字母，侧保存长度
  let letterWidth = 0;
  // 汉字宽度
  let chineseWidth = 14;
  // otherFont宽度
  let otherWidth = 7;
  for (let i = 0; i < len; i++) {
    if (/[\u4e00-\u9fa5]|[\uFE30-\uFFA0]/g.test(textArr[i])) {
      if (letterWidth > 0) {
        if (nodeWidth + chineseWidth + letterWidth * otherWidth > maxWidth) {
          rowText.push({
            type: 'text',
            content: text.substring(previousNode, i),
          });
          previousNode = i;
          nodeWidth = chineseWidth;
          letterWidth = 0;
        } else {
          nodeWidth += chineseWidth + letterWidth * otherWidth;
          letterWidth = 0;
        }
      } else {
        if (nodeWidth + chineseWidth > maxWidth) {
          rowText.push({
            type: 'text',
            content: text.substring(previousNode, i),
          });
          previousNode = i;
          nodeWidth = chineseWidth;
        } else {
          nodeWidth += chineseWidth;
        }
      }
    } else {
      if (/\n/g.test(textArr[i])) {
        rowText.push({
          type: 'break',
          content: text.substring(previousNode, i),
        });
        previousNode = i + 1;
        nodeWidth = 0;
        letterWidth = 0;
      } else if (textArr[i] == '\\' && textArr[i + 1] == 'n') {
        rowText.push({
          type: 'break',
          content: text.substring(previousNode, i),
        });
        previousNode = i + 2;
        nodeWidth = 0;
        letterWidth = 0;
      } else if (/[a-zA-Z0-9]/g.test(textArr[i])) {
        letterWidth += 1;
        if (nodeWidth + letterWidth * otherWidth > maxWidth) {
          rowText.push({
            type: 'text',
            content: text.substring(previousNode, i + 1 - letterWidth),
          });
          previousNode = i + 1 - letterWidth;
          nodeWidth = letterWidth * otherWidth;
          letterWidth = 0;
        }
      } else {
        if (nodeWidth + otherWidth > maxWidth) {
          rowText.push({
            type: 'text',
            content: text.substring(previousNode, i),
          });
          previousNode = i;
          nodeWidth = otherWidth;
        } else {
          nodeWidth += otherWidth;
        }
      }
    }
  }
  if (previousNode < len) {
    rowText.push({
      type: 'text',
      content: text.substring(previousNode, len),
    });
  }
  return rowText;
}

function downloadPopupDrawing(data) {
  // 以下为计算菜单的nview绘制布局，为固定算法，使用者无关关心
  const screenWidth = plus.screen.resolutionWidth;
  const screenHeight = plus.screen.resolutionHeight;
  //弹窗容器宽度
  popupViewWidth = screenWidth * 0.7;
  // 弹窗容器的Padding
  viewContentPadding = 20;
  // 弹窗容器的宽度
  viewContentWidth = popupViewWidth - viewContentPadding * 2;
  // 弹窗容器高度
  popupViewHeight = viewContentPadding * 3 + 60;
  let progressTip = data.progressTip || '准备下载...';
  let contentText = data.contentText || '正在为您更新，请耐心等待';

  let elementList = [
    {
      tag: 'rect', //背景色
      color: '#FFFFFF',
      rectStyles: {
        radius: '8px',
      },
    },
    {
      tag: 'font',
      id: 'title',
      text: '升级APP',
      textStyles: {
        size: '16px',
        color: '#333',
        weight: 'bold',
        verticalAlign: 'middle',
        whiteSpace: 'normal',
      },
      position: {
        top: viewContentPadding + 'px',
        height: '30px',
      },
    },
    {
      tag: 'font',
      id: 'content',
      text: contentText,
      textStyles: {
        size: '14px',
        color: '#333',
        verticalAlign: 'middle',
        whiteSpace: 'normal',
      },
      position: {
        top: viewContentPadding * 2 + 30 + 'px',
        height: '20px',
      },
    },
  ];

  // 是否有进度条
  if (data.progress) {
    popupViewHeight += viewContentPadding + 40;

    elementList = elementList.concat([
      {
        tag: 'font',
        id: 'progressValue',
        text: progressTip,
        textStyles: {
          size: '14px',
          color: $mainColor,
          whiteSpace: 'normal',
        },
        position: {
          top: viewContentPadding * 4 + 20 + 'px',
          height: '30px',
        },
      },
      {
        tag: 'rect', //绘制进度条背景
        id: 'progressBg',
        rectStyles: {
          radius: '4px',
          borderColor: $mainColor,
          borderWidth: '1px',
        },
        position: {
          top: viewContentPadding * 4 + 60 + 'px',
          left: viewContentPadding + 'px',
          width: viewContentWidth + 'px',
          height: '8px',
        },
      },
    ]);
  }
  if (data.buttonNum == 2) {
    popupViewHeight += viewContentPadding + 30;
    elementList = elementList.concat([
      {
        tag: 'rect', //绘制底边按钮
        rectStyles: {
          radius: '3px',
          borderColor: '#f1f1f1',
          borderWidth: '1px',
        },
        position: {
          bottom: viewContentPadding + 'px',
          left: viewContentPadding + 'px',
          width: (viewContentWidth - viewContentPadding) / 2 + 'px',
          height: '30px',
        },
      },
      {
        tag: 'rect', //绘制底边按钮
        rectStyles: {
          radius: '3px',
          color: '#ff00ff',
        },
        position: {
          bottom: viewContentPadding + 'px',
          left: (viewContentWidth - viewContentPadding) / 2 + viewContentPadding * 2 + 'px',
          width: (viewContentWidth - viewContentPadding) / 2 + 'px',
          height: '30px',
        },
      },
      {
        tag: 'font',
        id: 'cancelText',
        text: '取消下载',
        textStyles: {
          size: '14px',
          color: '#666',
          lineSpacing: '0%',
          whiteSpace: 'normal',
        },
        position: {
          bottom: viewContentPadding + 'px',
          left: viewContentPadding + 'px',
          width: (viewContentWidth - viewContentPadding) / 2 + 'px',
          height: '30px',
        },
      },
      {
        tag: 'font',
        id: 'confirmText',
        text: '后台下载',
        textStyles: {
          size: '14px',
          color: '#FFF',
          lineSpacing: '0%',
          whiteSpace: 'normal',
        },
        position: {
          bottom: viewContentPadding + 'px',
          left: (viewContentWidth - viewContentPadding) / 2 + viewContentPadding * 2 + 'px',
          width: (viewContentWidth - viewContentPadding) / 2 + 'px',
          height: '30px',
        },
      },
    ]);
  }
  if (data.buttonNum == 1) {
    popupViewHeight += viewContentPadding + 40;
    elementList = elementList.concat([
      {
        tag: 'rect', //绘制底边按钮
        id: 'inStallBtn',
        rectStyles: {
          radius: '6px',
          color: $mainColor,
        },
        position: {
          bottom: viewContentPadding + 'px',
          left: viewContentPadding + 'px',
          width: viewContentWidth + 'px',
          height: '40px',
        },
      },
      {
        tag: 'font',
        id: 'confirmText',
        text: '立即安装',
        textStyles: {
          size: '14px',
          color: '#FFF',
          lineSpacing: '0%',
        },
        position: {
          bottom: viewContentPadding + 'px',
          left: viewContentPadding + 'px',
          width: viewContentWidth + 'px',
          height: '40px',
        },
      },
    ]);
  }

  return {
    popupViewHeight: popupViewHeight,
    popupViewWidth: popupViewWidth,
    screenHeight: screenHeight,
    viewContentWidth: viewContentWidth,
    viewContentPadding: viewContentPadding,
    elementList: elementList,
  };
}

function downloadPopup(data, callback) {
  // 弹窗遮罩层
  let maskLayer = new plus.nativeObj.View('maskLayer', {
    //先创建遮罩层
    top: '0px',
    left: '0px',
    height: '100%',
    width: '100%',
    backgroundColor: 'rgba(0,0,0,0.5)',
  });
  let popupViewData = downloadPopupDrawing(data);

  // 弹窗内容
  let popupView = new plus.nativeObj.View('popupView', {
    //创建底部图标菜单
    tag: 'rect',
    top: (popupViewData.screenHeight - popupViewData.popupViewHeight) / 2 + 'px',
    left: '15%',
    height: popupViewData.popupViewHeight + 'px',
    width: '70%',
  });

  let progressValue = 0;
  let progressTip = 0;
  let contentText = 0;
  let buttonNum = 2;
  if (data.buttonNum >= 0) {
    buttonNum = data.buttonNum;
  }
  popupView.draw(popupViewData.elementList);
  let callbackData = {
    change: function (res) {
      let progressElement = [];
      if (res.progressValue) {
        progressValue = res.progressValue;
        // 绘制进度条
        progressElement.push({
          tag: 'rect', //绘制进度条背景
          id: 'progressValueBg',
          rectStyles: {
            radius: '4px',
            color: $mainColor,
          },
          position: {
            top: popupViewData.viewContentPadding * 4 + 60 + 'px',
            left: popupViewData.viewContentPadding + 'px',
            width:
              (plus.screen.resolutionWidth * 0.7 - viewContentPadding * 2) *
                (res.progressValue / 100) +
              'px',
            height: '8px',
          },
        });
      }
      if (res.progressTip) {
        progressTip = res.progressTip;
        progressElement.push({
          tag: 'font',
          id: 'progressValue',
          text: res.progressTip,
          textStyles: {
            size: '14px',
            color: $mainColor,
            whiteSpace: 'normal',
          },
          position: {
            top: popupViewData.viewContentPadding * 4 + 20 + 'px',
            height: '30px',
          },
        });
      }
      if (res.contentText) {
        contentText = res.contentText;
        progressElement.push({
          tag: 'font',
          id: 'content',
          text: res.contentText,
          textStyles: {
            size: '16px',
            color: '#333',
            whiteSpace: 'normal',
          },
          position: {
            top: popupViewData.viewContentPadding * 2 + 30 + 'px',
            height: '30px',
          },
        });
      }
      if (res.buttonNum >= 0 && buttonNum != res.buttonNum) {
        buttonNum = res.buttonNum;
        popupView.reset();
        popupViewData = downloadPopupDrawing(
          Object.assign(
            {
              progressValue: progressValue,
              progressTip: progressTip,
              contentText: contentText,
            },
            res,
          ),
        );
        let newElement = [];
        popupViewData.elementList.map((item, index) => {
          let have = false;
          progressElement.forEach((childItem, childIndex) => {
            if (item.id == childItem.id) {
              have = true;
            }
          });
          if (!have) {
            newElement.push(item);
          }
        });
        progressElement = newElement.concat(progressElement);
        popupView.setStyle({
          tag: 'rect',
          top: (popupViewData.screenHeight - popupViewData.popupViewHeight) / 2 + 'px',
          left: '15%',
          height: popupViewData.popupViewHeight + 'px',
          width: '70%',
        });
        popupView.draw(progressElement);
      } else {
        popupView.draw(progressElement);
      }
      data.filename = res.filename;
    },
    cancel: function () {
      maskLayer.hide();
      popupView.hide();
    },
    popupViewData,
  };
  popupView.addEventListener('click', function (e) {
    let maxTop = popupViewData.popupViewHeight - popupViewData.viewContentPadding;
    let maxLeft = plus.screen.resolutionWidth * 0.7 - popupViewData.viewContentPadding;
    if (e.clientY > maxTop - 40 && e.clientY < maxTop) {
      if (buttonNum == 1) {
        // 单按钮
        if (e.clientX > popupViewData.viewContentPadding && e.clientX < maxLeft) {
          maskLayer.hide();
          popupView.hide();
          popupView.reset();
          // var fileSaveUrl = plus.io.convertLocalFileSystemURL(data.filename);
          plus.runtime.openFile(data.filename, {}, function (error) {
            plus.nativeUI.toast(error.message);
          }); //选择软件打开文件

          callback && callback(callbackFun);
          // callbackData.reboot();
        }
      } else if (buttonNum == 2) {
        // 双按钮
        let buttonWidth = (popupViewData.viewContentWidth - popupViewData.viewContentPadding) / 2;
        if (
          e.clientX > popupViewData.viewContentPadding &&
          e.clientX < maxLeft - buttonWidth - popupViewData.viewContentPadding
        ) {
          maskLayer.hide();
          popupView.hide();
          callbackData.cancelDownload();
        } else if (e.clientX > maxLeft - buttonWidth && e.clientX < maxLeft) {
          maskLayer.hide();
          popupView.hide();
        }
      }
    }
  });
  // 显示弹窗
  maskLayer.show();
  popupView.show();
  // 改变进度条
  return callbackData;
}

// 新的下载
function newUpdateDownload(data, callback) {
  if (data.shichang === 1 && /\.apk/i.test(data.url)) {
    //去应用市场更新
    plus.runtime.openURL(data.shichangurl);
    plus.runtime.quit();
  } else {
    // 开始下载
    // 创建下载任务
    let dtask;
    let popupData = {
      progress: true,
      buttonNum: 0, //按钮的显示   0 ==> 无按钮，1 ==> 关闭按钮，2 ==> 取消下载和后台下载按钮
    };
    let lastProgressValue = 0;
    let popupObj = downloadPopup(popupData, callback);

    dtask = plus.downloader.createDownload(
      data.url,
      {
        filename: '_downloads/',
      },
      function (download, status) {
        if (status == 200) {
          // try {
          //   uni.removeSavedFile({
          //     filePath: plus.io.convertLocalFileSystemURL(download.filename),
          //     success: function () {
          //       console.log('文件删除成功');
          //     },
          //     fail: function (err) {
          //       console.log('文件删除失败', err);
          //     },
          //   });
          // } catch (error) {}

          popupObj.change({
            progressValue: 100,
            progressTip: '正在安装文件...',
            progress: true,
            buttonNum: 0,
          });
          plus.runtime.install(
            download.appName,
            { force: true },
            function () {
              uni.setStorageSync('changeVersion1', 1);
              popupObj.change({
                contentText: '应用资源下载完成！',
                buttonNum: 1,
                progress: false,
                filename: download.filename,
              });

              // var name = test.doc;   //文件名称可以在上传时进行保存，下载时取出，当文件名称中存在单双引号时，要做好处理，否则会报错
              // var dtask = plus.downloader.createDownload(url,{
              //   filename:"_downloads/"+name            //利用保存路径，实现下载文件的重命名
              // },function(d,status){
              //   //d为下载的文件对象
              //   if(status==200){
              //     //下载成功,d.filename是文件在保存在本地的相对路径，使用下面的API可转为平台绝对路径
              //     var fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
              //     plus.runtime.openFile(d.filename);	   //选择软件打开文件
              //     }else{
              //       //下载失败
              //       plus.downloader.clear();        //清除下载任务
              //     }
              // })
              // dtask.start();
            },
            function (e) {
              callback && callback(callbackFun);
              popupObj.cancel();
              plus.nativeUI.alert('安装文件失败[' + e.code + ']：' + e.message);
            },
          );
        } else {
          popupObj.change({
            contentText: '文件下载失败...',
            buttonNum: 1,
            progress: false,
          });
          callback && callback(callbackFun);
        }
      },
    );
    dtask.start();
    dtask.addEventListener('statechanged', function (task, status) {
      switch (task.state) {
        case 0: // 开始
        case 1: // 开始
          popupObj.change({
            progressValue: 0,
            progressTip: '准备下载...',
            progress: true,
          });
          break;
        case 2: // 已连接到服务器
          popupObj.change({
            progressValue: 0,
            progressTip: '开始下载...',
            progress: true,
          });
          break;
        case 3:
          const progress = parseInt((task.downloadedSize / task.totalSize) * 100);
          progressNum = progress;
          if (progress - lastProgressValue >= 2) {
            lastProgressValue = progress;
            popupObj.change({
              progressValue: progress,
              progressTip: '已下载' + progress + '%',
              progress: true,
            });
          }
          break;
      }
    });
    callbackFun = () => {
      const popView = plus.nativeObj.View.getViewById('popupView');
      const screenWidth = plus.screen.resolutionWidth;
      const screenHeight = plus.screen.resolutionHeight;
      //弹窗容器宽度
      popupViewWidth = screenWidth * 0.7;
      // 弹窗容器的宽度
      viewContentWidth = popupViewWidth - viewContentPadding * 2;
      popView.setStyle({
        tag: 'rect',
        top: (screenHeight - popupObj.popupViewData.popupViewHeight) / 2 + 'px',
        left: '15%',
        height: popupObj.popupViewData.popupViewHeight + 'px',
        width: '70%',
      });
      if (progressNum < 100) {
        popView.clearRect(
          {
            top: 20 * 4 + 60 + 'px',
            left: 20 + 'px',
          },
          'progressBg',
        );
        popView.drawRect(
          {
            borderColor: $mainColor,
            borderWidth: '1px',
            // size: '100%',
            radius: '4px',
          },
          {
            top: 20 * 4 + 60 + 'px',
            left: 20 + 'px',
            width: viewContentWidth + 'px',
            height: '8px',
          },
          'progressBg',
        );
      } else if (uni.getStorageSync('changeVersion1')) {
        popView.drawRect(
          {
            radius: '6px',
            color: $mainColor,
          },
          {
            bottom: viewContentPadding + 'px',
            left: viewContentPadding + 'px',
            width: viewContentWidth + 'px',
            height: '40px',
          },
          'inStallBtn',
        );
        popView.drawText(
          '立即安装',
          {
            bottom: viewContentPadding + 'px',
            left: viewContentPadding + 'px',
            width: viewContentWidth + 'px',
            height: '40px',
          },
          { color: '#FFF', lineSpacing: '0%', size: '14px' },
          'confirmText',
        );
      }
    };
    uni.onWindowResize(callbackFun);
    popupObj.cancelDownload = function () {
      dtask && dtask.abort();
      uni.showToast({
        title: '已取消下载',
        icon: 'none',
      });
    };
    // 重启APP
    popupObj.reboot = function () {
      plus.runtime.restart();
    };
  }
}
export { newUpdateDownload };
